// app.js

App({
    fetch: require('./utils/fetch'),
    onLaunch: function() {
        wx.showLoading({
          title: '登录中',
          mask: true
        })
        this.fetch('/user/checkLogin').then(data => {
            if (data.isLogin) {
                this.onUserLoginReady()
                console.log('通过保存的Cookie登录成功')
            } else {
                console.log('未登录')
                this.login({
                    success: () => {
                        this.onUserLoginReady()
                    },
                    fail: () => {
                        this.onLaunch()
                    }
                })
            }
        }, () => {
            this.onLaunch()
        })
    },
    login: function(options) {
        //options.success()
        //options.fail()
        //未登录
        wx.login({
            success: res => {
                console.log('微信登录临时代码：' + res.code)
                this.fetch('/user/login', {
                    js_code: res.code
                }).then(data => {
                    if (data && data.isLogin) {
                        options.success()
                    } else {
                        wx.hideLoading()
                        wx.showModal({
                          title: '登录失败（请使用真实的 AppID，并检查服务器端配置）',
                          confirmText: '重试',
                          success: res => {
                            if (res.confirm) {
                                options.fail()
                            }
                          }
                        })
                    }
                })
            },
            fail: res => {
                this.onLaunch()
            }
        })
    },
    onUserLoginReady: function() {
        wx.hideLoading()
        console.log('已登录')
    }
})
